package com.example.controller;

import com.example.constant.MessageConstant;
import com.example.result.Result;
import com.example.utils.AliOssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping
@Slf4j
@RequiredArgsConstructor
public class CommonController {

    private final AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}", file);
        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 拼接文件名
            String objectName = UUID.randomUUID().toString() + substring;
            // 调用阿里云文件上传方法
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.info("文件上传失败：{}", e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
